package com.fw.application.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.application.controller.base.BaseController;
import com.fw.common.Builder;
import com.fw.common.IdXD;
import com.fw.mes.Result;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.model.vo.GunsDetailVo;
import com.fw.system.web.model.vo.GunsLogVo;
import com.fw.system.web.model.vo.GunsUserVo;
import com.fw.system.web.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;

import static com.fw.mes.ResultUtils.success;

/**
 * <p>
 * 装备商品表 前端控制器
 * </p>
 *
 * @author
 * @since 2021-11-24
 */
@RestController
@RequestMapping("/guns")
@Api(tags = "裝備列表查看購買相關")
@CrossOrigin
public class TbGunsController implements BaseController {

    @Autowired
    private ITbGunsService gunsService;
    @Autowired
    private ITbMoneysService moneysService;
    @Autowired
    private IdXD idXD;
    @Autowired
    private ITbGunsLogService gunsLogService;
    @Autowired
    private ITbGunsUserService gunsUserService;
    @Autowired
    private ITbAmountLogService amountLogService;
    @Autowired
    private ITbVipLevelService vipLevelService;
    @Autowired
    private ITbRuleDatesService ruleDatesService;
    @Autowired
    private ITbCollectionService collectionService;

    @GetMapping("/getList")
    @ApiOperation("根據vip等級查詢列表 vipNum 對應的等級數字")
    public Result getList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam Integer vipNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<TbGuns> list = gunsService.list(Wrappers.<TbGuns>lambdaQuery().eq(TbGuns::getIsType, 1).eq(TbGuns::getGunsLevel, vipNum).eq(TbGuns::getIsType,1));
        PageInfo info = new PageInfo(list);
        return success(info);
    }

    @GetMapping("/getIndexList")
    @ApiOperation("首页调用查询列表最新时间排序")
    public Result getIndexList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<TbGuns> list = gunsService.list(Wrappers.<TbGuns>lambdaQuery().eq(TbGuns::getIsType, 1).eq(TbGuns::getIsType,1).orderByDesc(TbGuns::getCreateTime));
        PageInfo info = new PageInfo(list);
        return success(info);
    }

    @GetMapping("/getById")
    @ApiOperation("根據id得到詳情")
    public Result getById(@RequestParam(required = true) String id) {
        TbGuns guns = gunsService.getById(id);
        GunsDetailVo gunsDetailVo = new GunsDetailVo();
        TbUser us = getDefaultUser();
        if (us != null){
            if (guns != null){

                BeanUtil.copyProperties(guns,gunsDetailVo);
                TbCollection collection = collectionService.getOne(Wrappers.<TbCollection>lambdaQuery().eq(TbCollection::getUserId, this.getUser().getId()).eq(TbCollection::getGunsId, id)
                        .eq(TbCollection::getIsType,1));
                if (collection!=null){
                    gunsDetailVo.setCollectType(1);
                }
            }
        }else{
            BeanUtil.copyProperties(guns,gunsDetailVo);
        }

        return success(gunsDetailVo);
    }

    @GetMapping("/buyGunsById")
    @ApiOperation("購買裝備")
    public Result buyGunsById(@RequestParam String id) {
        TbUser user = this.getUser();
        TbRuleDates ruleDates = ruleDatesService.getById("1");
        if (LocalTime.now().compareTo(ruleDates.getRuleTime()) < 0)
            return new Result().fail(0, "未到交易时间");
        if (LocalTime.now().compareTo(ruleDates.getRuleEndTime()) > 0)
            return new Result().fail(0, "今日交易已结束");
        List<TbGunsUser> list = gunsUserService.list(Wrappers.<TbGunsUser>lambdaQuery().eq(TbGunsUser::getUserId, user.getId()).last("AND  TO_DAYS(create_time) = TO_DAYS(NOW())"));
        BigDecimal count = new BigDecimal("0");
        for (TbGunsUser gunsUser : list) {
            TbGuns guns = gunsService.getById(gunsUser.getGunsId());
            count = count.add(guns.getAmount());
        }
        TbVipLevel one = vipLevelService.getOne(Wrappers.<TbVipLevel>lambdaQuery().eq(TbVipLevel::getVipLevel, user.getVipLevel()));
        if (one == null)
            return new Result().fail(0, "您还没有VIP等级");
        if (count.compareTo(one.getDayAmount()) >= 0)
            return new Result().fail(0, "今日购买总额达到上限");
        if (list.size() > one.getDayNum())
            return new Result().fail(0, "今日单数达到上限");

        TbGuns guns = gunsService.getById(id);
        if (guns.getGunsNum() <= 0)
            return new Result().fail(0, "没有了，明天再来哦！");
        if (user.getVipLevel() <= 0)
            return new Result().fail(0, "您还没有VIP等级！");
        if (user.getVipLevel() < guns.getGunsLevel())
            return new Result().fail(0, "等级过低,请去升级VIP！");
        TbMoneys moneys = moneysService.getOne(Wrappers.<TbMoneys>lambdaQuery().eq(TbMoneys::getUserId, user.getId()));
        if (moneys.getAmount().compareTo(guns.getAmount()) < 0)
            return new Result().fail(0, "余额不足，请充值！");
        moneys.setAmount(moneys.getAmount().subtract(guns.getAmount()));
        moneysService.updateById(moneys);
        amountLogService.saveLog(user.getId(), "购买饰品", guns.getAmount(), 3, null);
        gunsLogService.gunsBuyLog(user.getId(), id, guns.getAmount(), 1);
        Builder.of(TbGunsUser::new).with(TbGunsUser::setId, idXD.nextId())
                .with(TbGunsUser::setCreateTime, LocalDateTime.now())
                .with(TbGunsUser::setGunsId, id)
                .with(TbGunsUser::setUserId, user.getId())
                .with(TbGunsUser::setIsStatus, 1).build().insert();
        return success();
    }


    @GetMapping("/sellOutGuns")
    @ApiOperation("卖出装备 传自己所属选择的那件装备的id")
    public Result sellOutGuns(@RequestParam String ids) {
        String userId = this.getUser().getId();
        String[] split = ids.split(",");
        TbRuleDates ruleDates = ruleDatesService.getById("2");
        if (LocalTime.now().compareTo(ruleDates.getRuleTime()) < 0)
            return new Result().fail(0, "未到卖出时间");
        if (LocalTime.now().compareTo(ruleDates.getRuleEndTime()) > 0)
            return new Result().fail(0, "今日卖出已结束");
        for (String s : split) {
            TbGunsUser gunsUser = gunsUserService.getById(s);
            if (gunsUser == null) {
                return new Result().fail(0, "未找到该饰品");
            }
            if (gunsUser.getIsStatus().equals(2))
                return new Result().fail(0, "已经出售");
            if (gunsUser.getIsStatus().equals(3))
                return new Result().fail(0, "冻结中");
            TbGuns guns = gunsService.getById(gunsUser.getGunsId());
            if (gunsUser.getCreateTime().plusHours(guns.getBuyHour()).compareTo(LocalDateTime.now()) > 0)
                return new Result().fail(0, "该饰品需要购买"+guns.getBuyHour()+"小时后才能卖出");
            gunsUser.setIsStatus(2);
            gunsUserService.updateById(gunsUser);

            gunsLogService.gunsBuyLog(userId, guns.getId(), guns.getZAmount(), 2);
            TbMoneys moneys = moneysService.getOne(Wrappers.<TbMoneys>lambdaQuery().eq(TbMoneys::getUserId, userId));
            moneys.setAmount(moneys.getAmount().add(guns.getZAmount()));
            moneysService.updateById(moneys);
            amountLogService.saveLog(userId, " 出售饰品", guns.getZAmount(), 4, null);
        }

        return success();
    }

    //查看我的装备列表
    @GetMapping("/getUserGunsList")
    @ApiOperation("查看我购买过的装备列表 默认查看待卖出 type 1待卖出 2卖出了 3封禁了")
    public Result<List<GunsUserVo>> getUserGunsList(@RequestParam(defaultValue = "1") Integer type, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        String userId = this.getUser().getId();
        PageHelper.startPage(pageNum, pageSize);
        List<GunsUserVo> collect = gunsUserService.list(Wrappers.<TbGunsUser>lambdaQuery().eq(TbGunsUser::getUserId, userId).eq(TbGunsUser::getIsStatus, type).orderByDesc(TbGunsUser::getCreateTime)).stream().map(item -> {
            GunsUserVo vo = Builder.of(GunsUserVo::new).build();
            BeanUtil.copyProperties(item, vo);
            TbGuns guns = gunsService.getById(item.getGunsId());
            vo.setAmount(guns.getAmount());
            vo.setGunsName(guns.getGunsName());
            vo.setGunsContent(guns.getGunsContent());
            vo.setGunsLevel(guns.getGunsLevel());
            vo.setZAmount(guns.getZAmount());
            vo.setGunsParam(guns.getGunsParam());
            vo.setImgUrl(guns.getImgUrl());
            vo.setCreateDate(item.getCreateTime());
            vo.setGunsId(item.getGunsId());
            vo.setBuyHour(guns.getBuyHour());
            vo.setBuyHour(guns.getBuyHour());
            return vo;
        }).collect(Collectors.toList());
        PageInfo<List<GunsUserVo>> listPageInfo = new PageInfo(collect);
        return success(collect);
    }

    //查询我的装备买入卖出记录
    @GetMapping("/gunsLogList")
    @ApiOperation("查询我的装备买入卖出记录 type 1买入 2卖出")
    public Result<PageInfo<GunsLogVo>> gunsLogList(@RequestParam(defaultValue = "1") Integer type, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        String userId = this.getUser().getId();
        PageHelper.startPage(pageNum, pageSize);
        List<GunsLogVo> collect = gunsLogService.list(Wrappers.<TbGunsLog>lambdaQuery().eq(TbGunsLog::getUserId, userId).eq(TbGunsLog::getIsType, type).orderByDesc(TbGunsLog::getCreateTime))
                .stream().map(item -> {
                    GunsLogVo build = Builder.of(GunsLogVo::new).build();
                    TbGuns guns = gunsService.getById(item.getGunsId());
                    build.setGunsName(guns.getGunsName());
                    build.setImgUrl(guns.getImgUrl());
                    if (type.equals(1)){
                        build.setAmount(guns.getAmount());
                    }else {
                        build.setAmount(guns.getZAmount());
                    }
                    build.setCreateTime(item.getCreateTime());
                    return build;
                }).collect(Collectors.toList());
        PageInfo<GunsLogVo> listPageInfo = new PageInfo(collect);
        return success(listPageInfo);
    }


}

